~ chicken-core (chicken-5) /manual/Module (chicken base)
Trap1[[tags: manual]]2[[toc:]]34== Module (chicken base)56Core procedures and macros, acting as basic extensions to the R5RS7standard and other essential features.89This module is used by default, unless a program is compiled with10the {{-explicit-use}} option.1112=== Numeric predicates1314These allow you to make a more precise differentiation between number15types and their properties, not provided by R5RS.1617==== fixnum?1819<procedure>(fixnum? X)</procedure>2021Returns {{#t}} if {{X}} is a fixnum, or {{#f}} otherwise.2223==== flonum?2425<procedure>(flonum? X)</procedure>2627Returns {{#t}} if {{X}} is a flonum, or {{#f}} otherwise.2829==== bignum?3031<procedure>(bignum? X)</procedure>3233Returns {{#t}} if {{X}} is a bignum (integer larger than fits in a34fixnum), or {{#f}} otherwise.3536==== exact-integer?3738<procedure>(exact-integer? X)</procedure>3940Returns {{#t}} if {{X}} is an exact integer (i.e., a fixnum or a41bignum), or {{#f}} otherwise.4243This procedure is compatible with the definition from the R7RS44{{(scheme base)}} library.4546==== cplxnum?4748<procedure>(cplxnum? X)</procedure>4950Returns {{#t}} if {{X}} is a true complex number (it has an imaginary51component), or {{#f}} otherwise.5253Please note that {{complex?}} will always return {{#t}} for any number54type supported by CHICKEN, so you can use this predicate if you want55to know the representational type of a number.5657==== ratnum?5859<procedure>(ratnum? X)</procedure>6061Returns {{#t}} if {{X}} is a true rational number (it is a fraction62with a denominator that's not 1), or {{#f}} otherwise.6364Please note that {{rational?}} will always return {{#t}} for any65number type supported by CHICKEN except complex numbers and non-finite66flonums, so you can use this predicate if you want to know the67representational type of a number.6869==== nan?7071<procedure>(nan? N)</procedure>7273Returns {{#t}} if {{N}} is not a number (a IEEE flonum NaN-value). If74{{N}} is a complex number, it's considered nan if it has a real or75imaginary component that's nan.7677This procedure is compatible with the definition from the R7RS78{{(scheme inexact)}} library.7980==== infinite?8182<procedure>(infinite? N)</procedure>8384Returns {{#t}} if {{N}} is negative or positive infinity, and {{#f}}85otherwise. If {{N}} is a complex number, it's considered infinite if86it has a real or imaginary component that's infinite.8788This procedure is compatible with the definition from the R7RS89{{(scheme inexact)}} library.9091==== finite?9293<procedure>(finite? N)</procedure>9495Returns {{#t}} if {{N}} represents a finite number and {{#f}}96otherwise. Positive and negative infinity as well as NaNs are not97considered finite. If {{N}} is a complex number, it's considered98finite if both the real and imaginary components are finite.99100This procedure is compatible with the definition from the R7RS101{{(scheme inexact)}} library.102103==== equal=?104105<procedure>(equal=? X y)</procedure>106107Similar to the standard procedure {{equal?}}, but compares numbers108using the {{=}} operator, so {{equal=?}} allows structural comparison109in combination with comparison of numerical data by value.110111112=== Arithmetic113114==== add1/sub1115116<procedure>(add1 N)</procedure>117<procedure>(sub1 N)</procedure>118119Adds/subtracts 1 from {{N}}.120121122==== exact-integer-sqrt123124<procedure>(exact-integer-sqrt K)</procedure>125126Returns two values {{s}} and {{r}}, where {{s^2 + r = K}} and {{K < (s+1)^2}}.127In other words, {{s}} is the closest square root we can find that's equal to or128smaller than {{K}}, and {{r}} is the rest if {{K}} isn't a neat square of two numbers.129130This procedure is compatible with the definition from the R7RS131{{(scheme base)}} library.132133==== exact-integer-nth-root134135<procedure>(exact-integer-nth-root K N)</procedure>136137Like {{exact-integer-sqrt}}, but with any base value. Calculates138{{\sqrt[N]{K}}}, the {{N}}th root of {{K}} and returns two values139{{s}} and {{r}} where {{s^N + r = K}} and {{K < (s+1)^N}}.140141142==== Division with quotient and remainder143144<procedure>(quotient&remainder X Y)</procedure>145<procedure>(quotient&modulo X Y)</procedure>146147Returns two values: the quotient and the remainder (or modulo) of148{{X}} divided by {{Y}}. Could be defined as {{(values (quotient X Y)149(remainder X Y))}}, but is much more efficient when dividing very150large numbers.151152==== signum153154<procedure>(signum N)</procedure>155156For real numbers, returns {{1}} if {{N}} is positive, {{-1}} if {{N}}157is negative or {{0}} if {{N}} is zero. {{signum}} is exactness158preserving.159160For complex numbers, returns a complex number of the same angle but161with magnitude 1.162163164=== Weak pairs165166''Weak pairs'' behave identically to regular pairs, with one167exception: the car value may be garbage collected. When that happens,168it gets replaced with a sentinel "broken-weak-pointer" value.169170They are indistinguishable from regular pairs: {{car}}, {{cdr}}, etc171all work on them, {{pair?}} returns true, etc. The {{WRITE}}172representation is identical to regular pairs, so they will be read173back as pairs. In other words, they have no read/write invariance.174175They're the same as regular pairs for all intents and purposes.176However, there's a {{weak-pair?}} predicate which ''can'' distinguish177between regular pairs and weak pairs.178179NOTE: Due to internal limitations, {{set-car!}} on a weak pair180currently may cause it to hold onto the value for one more GC cycle in181some situations.182183==== weak-cons184185<procedure>(weak-cons obj[1] obj[2])</procedure><br>186187Returns a newly allocated weak pair whose car is obj[1] and whose cdr188is obj[2]. The pair is indistinguishable from normal pairs, except as189noted above.190191 (weak-cons 'a '()) ===> (a)192 (weak-cons '(a) '(b c d)) ===> ((a) b c d)193 (weak-cons "a" '(b c)) ===> ("a" b c)194 (weak-cons 'a 3) ===> (a . 3)195 (weak-cons '(a b) 'c) ===> ((a b) . c)196197 (import (chicken gc))198199 (let* ((x '(a b))200 (y (weak-cons x 'c)))201 (gc #t)202 (car x)) ===> (a b)203204 (let ((x (weak-cons '(a b) 'c)))205 (gc #t)206 (car x)) ===> #!bwp207208As the final two examples show, when something ''else'' still holds on209to the value that's stored in the car of a weak pair, it will not be210reclaimed. But if the value is ''only'' referenced by one or more211weak pairs, it is reclaimed and the car of the weak pair is replaced212with the ''broken-weak-pointer'' value {{#!bwp}}.213214<procedure>(weak-pair? obj)</procedure><br>215216This predicate returns {{#t}} if and only if {{obj}} is a weak pair.217218 (weak-pair? (weak-cons 'a '())) ===> #t219 (weak-pair? (cons 'a '())) ===> #f220 (weak-pair? (vector 'a '())) ===> #f221222<procedure>(bwp-object? obj)</procedure>223224This predicate returns {{#t}} if {{obj}} is the broken-weak-pointer225value, otherwise {{#f}}.226227228=== Lazy evaluation229230==== delay-force231232<macro>(delay-force <expression>)</macro><br>233234The expression {{(delay-force expression)}} is conceptually similar to235{{(delay (force expression))}}, with the difference that forcing the236result of {{delay-force}} will in effect result in a tail call to237{{(force expression)}}, while forcing the result of238{{(delay (force expression))}} might not.239240Thus iterative lazy algorithms that might result in a long series of241chains of delay and force can be rewritten using delay-force to242prevent consuming unbounded space during evaluation.243244This special form is compatible with the definition from the R7RS245{{(scheme lazy)}} library.246247See the description of force under248[[Module scheme#control-features|Control features]] in the "scheme"249module documentation for a more complete description of delayed250evaluation.251252For more information regarding the unbounded build-up of space, see253the [[http://srfi.schemers.org/srfi-45/srfi-45.html|SRFI-45]]254rationale.255256==== make-promise257258<procedure>(make-promise obj)</procedure>259260The make-promise procedure returns a promise which, when forced, will261return {{obj}} . It is similar to {{delay}}, but does not delay its262argument: it is a procedure rather than syntax. If {{obj}} is already263a promise, it is returned.264265This procedure is compatible with the definition from the R7RS266{{(scheme lazy)}} library.267268269==== promise?270271<procedure>(promise? X)</procedure>272273Returns {{#t}} if {{X}} is a promise returned by {{delay}}, or274{{#f}} otherwise.275276This procedure is compatible with the definition from the R7RS277{{(scheme lazy)}} library.278279280=== Input/Output281282==== current-error-port283284<procedure>(current-error-port [PORT])</procedure>285286Returns default error output port. If {{PORT}} is given, then that287port is selected as the new current error output port.288289Note that the default error output port is not buffered. Use290[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]291if you need a different behaviour.292293==== print294295<procedure>(print [EXP1 ...])</procedure>296297Outputs the optional arguments {{EXP1 ...}} using {{display}} and298writes a newline character to the port that is the value of299{{(current-output-port)}}. Returns {{(void)}}.300301==== print*302303<procedure>(print* [EXP1 ...])</procedure>304305Similar to {{print}}, but does not output a terminating newline306character and performs a {{flush-output}} after writing its arguments.307308309=== Interrupts and error-handling310311==== enable-warnings312313<procedure>(enable-warnings [BOOL])</procedure>314315Enables or disables warnings, depending on wether {{BOOL}} is true or316false. If called with no arguments, this procedure returns {{#t}} if317warnings are currently enabled, or {{#f}} otherwise. Note that this is318not a parameter. The current state (whether warnings are enabled or319disabled) is global and not thread-local.320321322==== error323324<procedure>(error [LOCATION] [STRING] EXP ...)</procedure>325326Prints error message, writes all extra arguments to the value of327{{(current-error-port)}} and invokes the current328exception-handler. This conforms to329[[http://srfi.schemers.org/srfi-23/srfi-23.html|SRFI-23]]. If330{{LOCATION}} is given and a symbol, it specifies the ''location'' (the331name of the procedure) where the error occurred.332333334==== assert335336<macro>(assert EXP [OBJ ...])</macro>337338Evaluates {{EXP}}, if it returns #f, {{error}} is applied to {{OBJ ...}},339else the result of {{EXP}} is returned.340When compiling in unsafe mode, assertions of this kind are disabled.341342343==== get-call-chain344345<procedure>(get-call-chain [START [THREAD]])</procedure>346347Returns a list with the call history. Backtrace information is only348generated in code compiled without {{-no-trace}} and evaluated code.349If the optional argument {{START}} is given, the backtrace starts at350this offset, i.e. when {{START}} is 1, the next to last trace-entry is351printed, and so on. If the optional argument {{THREAD}} is given, then352the call-chain will only be constructed for calls performed by this353thread.354355356357==== print-call-chain358359<procedure>(print-call-chain [PORT [START [THREAD [HEADER]]]])</procedure>360361Prints a backtrace of the procedure call history to {{PORT}}, which362defaults to {{(current-output-port)}}. The output is prefixed by the363{{HEADER}}, which defaults to {{"\n\tCall history:\n"}}.364365366==== procedure-information367368<procedure>(procedure-information PROC)</procedure>369370Returns an s-expression with debug information for the procedure371{{PROC}}, or {{#f}}, if {{PROC}} has no associated debug information.372373374==== warning375376<procedure>(warning MESSAGE [EXP ...])</procedure>377378Displays a warning message (if warnings are enabled with {{enable-warnings}}),379from the {{MESSAGE}}, and optional {{EXP}} arguments, then continues execution.380{{MESSAGE}}, and {{EXP}}, may be {{any}} object.381382383=== Lists384385==== alist-ref386387<procedure>(alist-ref KEY ALIST [TEST [DEFAULT]])</procedure>388389Looks up {{KEY}} in {{ALIST}} using {{TEST}} as the comparison function (or {{eqv?}} if390no test was given) and returns the cdr of the found pair, or {{DEFAULT}} (which defaults to {{#f}}).391392393==== alist-update394395<procedure>(alist-update KEY VALUE ALIST [TEST])</procedure>396<procedure>(alist-update! KEY VALUE ALIST [TEST])</procedure>397398If the list {{ALIST}} contains a pair of the form {{(KEY . X)}}, then this procedure399replaces {{X}} with {{VALUE}} and returns {{ALIST}}. If {{ALIST}} contains no such item, then400{{alist-update}} returns {{((KEY . VALUE) . ALIST)}}. The optional argument401{{TEST}} specifies the comparison procedure to search a matching pair in {{ALIST}}402and defaults to {{eqv?}}. {{alist-update!}} is the destructive version of {{alist-update}}.403404405==== atom?406407<procedure>(atom? X)</procedure>408409Returns {{#t}} if {{X}} is not a pair.410411412==== butlast413414<procedure>(butlast LIST)</procedure>415416Returns a fresh list with all elements but the last of {{LIST}}.417418419==== chop420421<procedure>(chop LIST N)</procedure>422423Returns a new list of sublists, where each sublist contains {{N}}424elements of {{LIST}}. If {{LIST}} has a length that is not425a multiple of {{N}}, then the last sublist contains the remaining426elements.427428<enscript highlight=scheme>429(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))430(chop '(a b c d) 3) ==> ((a b c) (d))431</enscript>432433434==== compress435436<procedure>(compress BLIST LIST)</procedure>437438Returns a new list with elements taken from {{LIST}} with439corresponding true values in the list {{BLIST}}.440441<enscript highlight=scheme>442(define nums '(99 100 110 401 1234))443(compress (map odd? nums) nums) ==> (99 401)444</enscript>445446447==== flatten448449<procedure>(flatten LIST1 ...)</procedure>450451Returns {{LIST1 ...}} concatenated together, with nested lists452removed (flattened).453454455==== foldl456457<procedure>(foldl PROCEDURE INIT LIST)</procedure>458459Applies {{PROCEDURE}} to the elements from {{LIST}}, beginning from460the left:461462<enscript hightlight=scheme>463(foldl + 0 '(1 2 3)) ==> (+ (+ (+ 0 1) 2) 3)464</enscript>465466Note that the order of arguments taken by {{PROCEDURE}} is different467from the {{SRFI-1}} {{fold}} procedure, but matches the more natural468order used in Haskell and Objective Caml.469470471==== foldr472473<procedure>(foldr PROCEDURE INIT LIST)</procedure>474475Applies {{PROCEDURE}} to the elements from {{LIST}}, beginning from476the right:477478<enscript hightlight=scheme>479(foldr + 0 '(1 2 3)) ==> (+ 1 (+ 2 (+ 3 0)))480</enscript>481482483==== intersperse484485<procedure>(intersperse LIST X)</procedure>486487Returns a new list with {{X}} placed between each element.488489490==== join491492<procedure>(join LISTOFLISTS [LIST])</procedure>493494Concatenates the lists in {{LISTOFLISTS}} with {{LIST}} placed495between each sublist. {{LIST}} defaults to the empty list.496497<enscript highlight=scheme>498(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)499(join '((p q) () (r (s) t)) '(-)) ==> (p q - - r (s) t)500</enscript>501502{{join}} could be implemented as follows:503504<enscript highlight=scheme>505(define (join lstoflsts #!optional (lst '()))506 (apply append (intersperse lstoflists lst)) )507</enscript>508509510==== rassoc511512<procedure>(rassoc KEY LIST [TEST])</procedure>513514Similar to {{assoc}}, but compares {{KEY}} with the {{cdr}} of each pair in {{LIST}} using515{{TEST}} as the comparison procedures (which defaults to {{eqv?}}).516517518==== tail?519520<procedure>(tail? X LIST)</procedure>521522Returns true if {{X}} is one of the tails (cdr's) of {{LIST}}.523524525=== Vectors526527==== vector-copy!528529<procedure>(vector-copy! VECTOR1 VECTOR2 [COUNT])</procedure>530531Copies contents of {{VECTOR1}} into {{VECTOR2}}. If the532argument {{COUNT}} is given, it specifies the maximal number of533elements to be copied. If not given, the minimum of the lengths of the534argument vectors is copied.535536Exceptions: {{(exn bounds)}}537538==== vector-resize539540<procedure>(vector-resize VECTOR N [INIT])</procedure>541542Creates and returns a new vector with the contents of {{VECTOR}} and543length {{N}}. If {{N}} is greater than the original length of544{{VECTOR}}, then all additional items are initialized to {{INIT}}. If545{{INIT}} is not specified, the contents are initialized to some546unspecified value.547548549==== subvector550551<procedure>(subvector VECTOR FROM [TO])</procedure>552553Returns a new vector with elements taken from {{VECTOR}} in the554given range. {{TO}} defaults to {{(vector-length VECTOR)}}.555556{{subvector}} was introduced in CHICKEN 4.7.3.557558559=== Combinators560561562==== constantly563564<procedure>(constantly X ...)</procedure>565566Returns a procedure that always returns the values {{X ...}} regardless of the number and value of its arguments.567568<enscript highlight=scheme>569(constantly X) <=> (lambda args X)570</enscript>571572573==== complement574575<procedure>(complement PROC)</procedure>576577Returns a procedure that returns the boolean inverse of {{PROC}}.578579<enscript highlight=scheme>580(complement PROC) <=> (lambda (x) (not (PROC x)))581</enscript>582583584==== compose585586<procedure>(compose PROC1 PROC2 ...)</procedure>587588Returns a procedure that represents the composition of the589argument-procedures {{PROC1 PROC2 ...}}.590591<enscript highlight=scheme>592(compose F G) <=> (lambda args593 (call-with-values594 (lambda () (apply G args))595 F))596</enscript>597598{{(compose)}} is equivalent to {{values}}.599600601==== conjoin602603<procedure>(conjoin PRED ...)</procedure>604605Returns a procedure that returns {{#t}} if its argument satisfies the606predicates {{PRED ...}}.607<enscript highlight=scheme>608((conjoin odd? positive?) 33) ==> #t609((conjoin odd? positive?) -33) ==> #f610</enscript>611612613==== disjoin614615<procedure>(disjoin PRED ...)</procedure>616617Returns a procedure that returns {{#t}} if its argument satisfies any618predicate {{PRED ...}}.619<enscript highlight=scheme>620((disjoin odd? positive?) 32) ==> #t621((disjoin odd? positive?) -32) ==> #f622</enscript>623624625==== each626627<procedure>(each PROC ...)</procedure>628629Returns a procedure that applies {{PROC ...}} to its arguments, and returns the result(s)630of the last procedure application. For example631632<enscript highlight=scheme>633(each pp eval)634</enscript>635636is equivalent to637638<enscript highlight=scheme>639(lambda args640 (apply pp args)641 (apply eval args) )642</enscript>643644{{(each PROC)}} is equivalent to {{PROC}} and {{(each)}} is equivalent to645{{void}}.646647648==== flip649650<procedure>(flip PROC)</procedure>651652Returns a two-argument procedure that calls {{PROC}} with its653arguments swapped:654<enscript highlight=scheme>655(flip PROC) <=> (lambda (x y) (PROC y x))656</enscript>657658659==== identity660661<procedure>(identity X)</procedure>662663Returns its sole argument {{X}}.664665666==== list-of?667668<procedure>(list-of? PRED)</procedure>669670Returns a procedure of one argument that returns {{#t}} when671applied to a list of elements that all satisfy the predicate procedure672{{PRED}}, or {{#f}} otherwise.673674<enscript highlight=scheme>675((list-of? even?) '(1 2 3)) ==> #f676((list-of? number?) '(1 2 3)) ==> #t677</enscript>678679680==== o681682<procedure>(o PROC ...)</procedure>683684A single value version of {{compose}} (slightly faster). {{(o)}} is equivalent685to {{identity}}.686687688=== User-defined named characters689690==== char-name691692<procedure>(char-name SYMBOL-OR-CHAR [CHAR])</procedure>693694This procedure can be used to inquire about character names or to695define new ones. With a single argument the behavior is as follows:696If {{SYMBOL-OR-CHAR}} is a symbol, then {{char-name}} returns697the character with this name, or {{#f}} if no character is defined698under this name. If {{SYMBOL-OR-CHAR}} is a character, then the699name of the character is returned as a symbol, or {{#f}} if the700character has no associated name.701702If the optional argument {{CHAR}} is provided, then703{{SYMBOL-OR-CHAR}} should be a symbol that will be the new name of704the given character. If multiple names designate the same character,705then the {{write}} will use the character name that was defined last.706707<enscript highlight=scheme>708(char-name 'space) ==> #\space709(char-name #\space) ==> space710(char-name 'bell) ==> #f711(char-name (integer->char 7)) ==> #f712(char-name 'bell (integer->char 7))713(char-name 'bell) ==> #\bell714(char->integer (char-name 'bell)) ==> 7715</enscript>716717718=== The unspecified value719720==== void721722<procedure>(void ARGUMENT ...)</procedure>723724Ignores {{ARGUMENT ...}} and returns an unspecified value.725726727=== Continuations728729==== call/cc730731<procedure>(call/cc PROCEDURE)</procedure>732733An alias for {{call-with-current-continuation}}.734735This procedure is compatible with the definition from the R7RS736{{(scheme base)}} library.737738=== Symbols739740==== Symbol utilities741742===== symbol-append743744<procedure>(symbol-append SYMBOL1 ...)</procedure>745746Creates a new symbol from the concatenated names of the argument symbols747{{(SYMBOL1 ...)}}.748749==== Uninterned symbols ("gensyms")750751Symbols may be "interned" or "uninterned". Interned symbols are752registered in a global table, and when read back from a port are753identical to a symbol written before:754755<enscript highlight=scheme>756(define sym 'foo)757758(eq? sym (with-input-from-string759 (with-output-to-string760 (lambda () (write sym)))761 read))762763 => #t764</enscript>765766Uninterned symbols on the other hand are not globally registered and so767multiple symbols with the same name may coexist:768769<enscript highlight=scheme>770(define sym (gensym 'foo)) ; sym is a uninterned symbol like "foo42"771772(eq? sym (with-input-from-string ; the symbol read will be an interned symbol773 (with-output-to-string774 (lambda () (write sym)))775 read))776777 => #f778779(eq? (string->uninterned-symbol "foo") (string->uninterned-symbol "foo"))780781 => #f782</enscript>783784Use uninterned symbols if you need to generate unique values that785can be compared quickly, for example as keys into a hash-table786or association list. Note that uninterned symbols lose their787uniqueness property when written to a file and read back in, as788in the example above.789790===== gensym791792<procedure>(gensym [STRING-OR-SYMBOL])</procedure>793794Returns a newly created uninterned symbol. If an argument is provided,795the new symbol is prefixed with that argument.796797798===== string->uninterned-symbol799800<procedure>(string->uninterned-symbol STRING)</procedure>801802Returns a newly created, unique symbol with the name {{STRING}}.803804805=== Setters806807SRFI-17 is fully implemented. For more information see:808[[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].809810==== setter811812<procedure>(setter PROCEDURE)</procedure>813814Returns the setter-procedure of {{PROCEDURE}}, or signals an error if815{{PROCEDURE}} has no associated setter-procedure.816817Note that {{(set! (setter PROC) ...)}} for a procedure that has no818associated setter procedure yet is a very slow operation (the old819procedure is replaced by a modified copy, which involves a garbage820collection).821822823==== getter-with-setter824825<procedure>(getter-with-setter GETTER SETTER)</procedure>826827Returns a copy of the procedure {{GETTER}} with the associated setter828procedure {{SETTER}}. Contrary to the SRFI specification, the setter829of the returned procedure may be changed.830831832=== Binding forms for optional arguments833834==== optional835836<macro>(optional ARGS DEFAULT)</macro>837838Use this form for procedures that take a single optional argument. If839{{ARGS}} is the empty list {{DEFAULT}} is evaluated and840returned, otherwise the first element of the list {{ARGS}}. It is841an error if {{ARGS}} contains more than one value.842843<enscript highlight=scheme>844(define (incr x . i) (+ x (optional i 1)))845(incr 10) ==> 11846(incr 12 5) ==> 17847</enscript>848849850==== case-lambda851852<macro>(case-lambda (LAMBDA-LIST1 EXP1 ...) ...)</macro>853854Expands into a lambda that invokes the body following the first855matching lambda-list.856857<enscript highlight=scheme>858(define plus859 (case-lambda860 (() 0)861 ((x) x)862 ((x y) (+ x y))863 ((x y z) (+ (+ x y) z))864 (args (apply + args))))865866(plus) ==> 0867(plus 1) ==> 1868(plus 1 2 3) ==> 6869</enscript>870871For more information see the documentation for872[[http://srfi.schemers.org/srfi-16/srfi-16.html|SRFI-16]]873874This special form is also compatible with the definition from the R7RS875{{(scheme case-lambda)}} library.876877==== let-optionals878879<macro> (let-optionals ARGS ((VAR1 DEFAULT1) ...) BODY ...)</macro>880881Binding constructs for optional procedure arguments. {{ARGS}} is882normally a rest-parameter taken from a lambda-list. {{let-optionals}}883binds {{VAR1 ...}} to available arguments in parallel, or to884{{DEFAULT1 ...}} if not enough arguments were provided.885{{let-optionals*}} binds {{VAR1 ...}} sequentially, so every variable886sees the previous ones. it is an error if any excess arguments are887provided.888889<enscript highlight=scheme>890(let-optionals '(one two) ((a 1) (b 2) (c 3))891 (list a b c) ) ==> (one two 3)892</enscript>893894==== let-optionals*895896<macro> (let-optionals* ARGS ((VAR1 DEFAULT1) ... [RESTVAR]) BODY ...)</macro>897898Binding constructs for optional procedure arguments. {{ARGS}} is899normally a rest-parameter taken from a lambda-list. {{let-optionals}}900binds {{VAR1 ...}} to available arguments in parallel, or to901{{DEFAULT1 ...}} if not enough arguments were provided.902{{let-optionals*}} binds {{VAR1 ...}} sequentially, so every variable903sees the previous ones. If a single variable {{RESTVAR}} is given,904then it is bound to any remaining arguments, otherwise it is an error905if any excess arguments are provided.906907<enscript highlight=scheme>908(let-optionals* '(one two) ((a 1) (b 2) (c a))909 (list a b c) ) ==> (one two one)910</enscript>911912=== Other binding forms913914==== and-let*915916<macro>(and-let* (BINDING ...) EXP1 EXP2 ...)</macro>917918Bind sequentially and execute body. {{BINDING}} can919be a list of a variable and an expression, a list with a single920expression, or a single variable. If the value of an expression921bound to a variable is {{#f}}, the {{and-let*}} form922evaluates to {{#f}} (and the subsequent bindings and the body923are not executed). Otherwise the next binding is performed. If924all bindings/expressions evaluate to a true result, the body is925executed normally and the result of the last expression is the926result of the {{and-let*}} form. See also the documentation for927[[http://srfi.schemers.org/srfi-2/srfi-2.html|SRFI-2]].928929==== letrec*930931<macro>(letrec* ((VARIABLE EXPRESSION) ...) BODY ...)</macro>932933Implements R6RS/R7RS {{letrec*}}. {{letrec*}} is similar to {{letrec}}934but binds the variables sequentially and is to {{letrec}} what935{{let*}} is to {{let}}.936937This special form is compatible with the definition from the R7RS938{{(scheme base)}} library.939940==== rec941942<macro>(rec NAME EXPRESSION)</macro><br>943<macro>(rec (NAME VARIABLE ...) BODY ...)</macro>944945Allows simple definition of recursive definitions. {{(rec NAME EXPRESSION)}} is946equivalent to {{(letrec ((NAME EXPRESSION)) NAME)}} and {{(rec (NAME VARIABLE ...) BODY ...)}}947is the same as {{(letrec ((NAME (lambda (VARIABLE ...) BODY ...))) NAME)}}.948949==== cut950951<macro>(cut SLOT ...)</macro><br>952<macro>(cute SLOT ...)</macro>953954[[http://srfi.schemers.org/srfi-26/srfi-26.html|Syntactic sugar for specializing parameters]].955956==== define-values957958<macro>(define-values (NAME ...) VALUEEXP)</macro>959<macro>(define-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)</macro>960<macro>(define-values NAME VALUEEXP)</macro>961962Defines several variables at once, with the result values of expression963{{VALUEEXP}}, similar to {{set!-values}}.964965This special form is compatible with the definition from the R7RS966{{(scheme base)}} library.967968==== fluid-let969970<macro>(fluid-let ((VAR1 X1) ...) BODY ...)</macro>971972Binds the variables {{VAR1 ...}} dynamically to the values {{X1 ...}}973during execution of {{BODY ...}}. This implements974[[http://srfi.schemers.org/srfi-15/srfi-15.html|SRFI-15]].975976==== let-values977978<macro>(let-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>979980Binds multiple variables to the result values of {{VALUEEXP ...}}.981All variables are bound simultaneously. Like {{define-values}}, the982{{(NAME ...)}} expression can be any basic lambda list (dotted tail983notation is supported).984985This special form implements986[[http://srfi.schemers.org/srfi-11/srfi-11.html|SRFI-11]], and it is987also compatible with the definition from the R7RS {{(scheme base)}}988library.989990991==== let*-values992993<macro>(let*-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>994995Binds multiple variables to the result values of {{VALUEEXP ...}}.996The variables are bound sequentially. Like {{let-values}}, the997{{(NAME ...)}} expression can be any basic lambda list (dotted tail998notation is supported).9991000This is also part of1001[[http://srfi.schemers.org/srfi-11/srfi-11.html|SRFI-11]] and is also1002compatible with the definition from the R7RS {{(scheme base)}}1003library.10041005<enscript highlight=scheme>1006(let*-values (((a b) (values 2 3))1007 ((p) (+ a b)) )1008 p) ==> 51009</enscript>10101011==== letrec-values10121013<macro>(letrec-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>10141015Binds the result values of {{VALUEEXP ...}} to multiple variables at1016once. All variables are mutually recursive. Like {{let-values}}, the1017{{(NAME ...)}} expression can be any basic lambda list (dotted tail1018notation is supported).10191020<enscript highlight=scheme>1021(letrec-values (((odd even)1022 (values1023 (lambda (n) (if (zero? n) #f (even (sub1 n))))1024 (lambda (n) (if (zero? n) #t (odd (sub1 n)))) ) ) )1025 (odd 17) ) ==> #t1026</enscript>102710281029==== receive10301031<macro>(receive (NAME ...) VALUEEXP BODY ...)</macro><br>1032<macro>(receive (NAME1 ... NAMEn . NAMEn+1) VALUEEXP BODY ...)</macro><br>1033<macro>(receive NAME VALUEEXP BODY ...)</macro><br>1034<macro>(receive VALUEEXP)</macro>10351036[[http://srfi.schemers.org/srfi-8/srfi-8.html|SRFI-8]].1037Syntactic sugar for {{call-with-values}}. Binds variables1038to the result values of {{VALUEEXP}} and evaluates {{BODY ...}},1039similar {{define-values}} but lexically scoped.10401041{{(receive VALUEEXP)}} is equivalent to {{(receive _ VALUEEXP _)}}.1042This shortened form is not described by SRFI-8.10431044==== set!-values10451046<macro>(set!-values (NAME ...) VALUEEXP)</macro>1047<macro>(set!-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)</macro>1048<macro>(set!-values NAME VALUEEXP)</macro>10491050Assigns the result values of expression {{VALUEEXP}} to multiple1051variables, similar to {{define-values}}.10521053==== nth-value10541055<macro>(nth-value N EXP)</macro>10561057Returns the {{N}}th value (counting from zero) of the values returned1058by expression {{EXP}}.105910601061=== Parameters10621063Parameters are CHICKEN's form of dynamic variables, except that they are1064procedures rather than actual variables. A parameter is a procedure of1065zero or one arguments. To retrieve the value of a parameter call the1066parameter-procedure with zero arguments. To change the setting of the1067parameter, call the parameter-procedure with the new value as argument:10681069<enscript highlight=scheme>1070(define foo (make-parameter 123))1071(foo) ==> 1231072(foo 99)1073(foo) ==> 991074</enscript>10751076Parameters are fully thread-local, each thread of execution1077owns a local copy of a parameters' value.10781079CHICKEN implements1080[[http://srfi.schemers.org/srfi-39/srfi-39.html|SRFI-39]], which1081is also standardized by R7RS.108210831084==== parameterize10851086<macro>(parameterize ((PARAMETER1 X1) ...) BODY ...)</macro>10871088Binds the parameters {{PARAMETER1 ...}} dynamically to the values1089{{X1 ...}} during execution of {{BODY ...}}. (see also:1090{{make-parameter}} in [[Parameters]]). Note that {{PARAMETER}} may1091be any expression that evaluates to a parameter procedure.10921093This special form is compatible with the definition from the R7RS1094{{(scheme base)}} library.10951096==== make-parameter10971098<procedure>(make-parameter VALUE [GUARD])</procedure>10991100Returns a procedure that accepts zero or one argument. Invoking the1101procedure with zero arguments returns {{VALUE}}. Invoking the1102procedure with one argument changes its value to the value of that1103argument and returns the new value (subsequent invocations with zero1104parameters return the new value). {{GUARD}} should be a procedure of a1105single argument. Any new values of the parameter (even the initial1106value) are passed to this procedure. The guard procedure should check1107the value and/or convert it to an appropriate form.11081109This special form is compatible with the definition from the R7RS1110{{(scheme base)}} library.11111112=== Substitution forms and macros11131114==== define-constant11151116<macro>(define-constant NAME CONST)</macro>11171118Defines a variable with a constant value, evaluated at compile-time.1119Any reference to such a constant should appear textually '''after'''1120its definition. This construct is equivalent to {{define}} when1121evaluated or interpreted. Constant definitions should only appear at1122toplevel. Note that constants are local to the current compilation1123unit and are not available outside of the source file in which they1124are defined. Names of constants still exist in the Scheme namespace1125and can be lexically shadowed. If the value is mutable, then the1126compiler is careful to preserve its identity. {{CONST}} may be any1127constant expression, and may also refer to constants defined via1128{{define-constant}} previously, but it must be possible to1129evaluate the expression at compile-time.11301131==== define-inline11321133<macro>(define-inline (NAME VAR ...) BODY ...)</macro><br>1134<macro>(define-inline (NAME VAR ... . VAR) BODY ...)</macro><br>1135<macro>(define-inline NAME EXP)</macro>11361137Defines an inline procedure. Any occurrence of {{NAME}} will be replaced1138by {{EXP}} or {{(lambda (VAR ... [. VAR]) BODY ...)}}. This is similar1139to a macro, but variable names and scope are handled correctly.11401141Inline substitutions take place '''after''' macro-expansion, and any1142reference to {{NAME}} should appear textually '''after''' its1143definition. Inline procedures are local to the current compilation unit1144and are not available outside of the source file in which they are1145defined. Names of inline procedures still exist in the Scheme namespace1146and can be lexically shadowed. Inline definitions should only appear at1147the toplevel.11481149Note that the {{inline-limit}} compiler option does not affect inline1150procedure expansion, and self-referential inline procedures may cause1151the compiler to enter an infinite loop.11521153In the third form, {{EXP}} must be a lambda expression.11541155This construct is equivalent to {{define}} when evaluated or1156interpreted.115711581159=== Conditional forms11601161==== unless11621163<macro>(unless TEST EXP1 EXP2 ...)</macro>11641165Equivalent to:11661167<enscript highlight=scheme>1168(if (not TEST) (begin EXP1 EXP2 ...))1169</enscript>11701171==== when11721173<macro>(when TEST EXP1 EXP2 ...)</macro>11741175Equivalent to:11761177<enscript highlight=scheme>1178(if TEST (begin EXP1 EXP2 ...))1179</enscript>118011811182=== Record structures11831184==== define-record11851186<macro>(define-record NAME SLOTNAME ...)</macro>11871188Defines a record type. This defines a number of procedures for1189creating, accessing, and modifying record members.11901191Call {{make-NAME}} to create an instance1192of the structure (with one initialization-argument for each slot, in1193the listed order).11941195{{(NAME? STRUCT)}} tests any object for being an instance of this1196structure.11971198Slots are accessed via {{(NAME-SLOTNAME STRUCT)}}1199and updated using {{(NAME-SLOTNAME-set!}} {{STRUCT}} {{VALUE)}}.12001201<enscript highlight=scheme>1202(define-record point x y)1203(define p1 (make-point 123 456))1204(point? p1) ==> #t1205(point-x p1) ==> 1231206(point-y-set! p1 99)1207(point-y p1) ==> 991208</enscript>12091210===== SRFI-17 setters12111212{{SLOTNAME}} may alternatively also be of the form12131214 (setter SLOTNAME)12151216In this case the slot can be read with {{(NAME-SLOTNAME STRUCT)}} as usual,1217and modified with {{(set! (NAME-SLOTNAME STRUCT) VALUE)}} (the slot-accessor1218has an associated SRFI-17 "setter" procedure) instead of1219the usual {{(NAME-SLOTNAME-set!}} {{STRUCT}} {{VALUE)}}.122012211222<enscript highlight=scheme>1223(define-record point (setter x) (setter y))1224(define p1 (make-point 123 456))1225(point? p1) ==> #t1226(point-x p1) ==> 1231227(set! (point-y p1) 99)1228(point-y p1) ==> 991229</enscript>12301231==== define-record-type12321233<macro>(define-record-type NAME (CONSTRUCTOR TAG ...) PREDICATE (FIELD ACCESSOR [MODIFIER]) ...)</macro>12341235SRFI-9 record types. For more information see the documentation for1236[[http://srfi.schemers.org/srfi-9/srfi-9.html|SRFI-9]].12371238As an extension the {{MODIFIER}} may have the form1239{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure1240for the given {{PROCEDURE}} that sets the field value.1241Usually {{PROCEDURE}} has the same name is {{ACCESSOR}} (but it1242doesn't have to).12431244This special form is also compatible with the definition from the R7RS1245{{(scheme base)}} library.12461247==== record-printer12481249<procedure>(record-printer NAME)</procedure><br>12501251Returns the procedure used to print records of the type {{NAME}} if1252one has been set with {{set-record-printer!}}, {{#f}} otherwise.12531254==== set-record-printer!12551256<procedure>(set-record-printer! NAME PROCEDURE)</procedure><br>1257<procedure>(set! (record-printer NAME) PROCEDURE)</procedure>12581259Defines a printing method for record of the type {{NAME}} by1260associating a procedure with the record type. When a record of this1261type is written using {{display, write}} or {{print}}, then1262the procedure is called with two arguments: the record to be printed1263and an output-port.12641265<enscript highlight=scheme>1266(define-record-type foo (make-foo x y z) foo?1267 (x foo-x)1268 (y foo-y)1269 (z foo-z))1270(define f (make-foo 1 2 3))1271(set-record-printer! foo1272 (lambda (x out)1273 (fprintf out "#,(foo ~S ~S ~S)"1274 (foo-x x) (foo-y x) (foo-z x))))1275(define-reader-ctor 'foo make-foo)1276(define s (with-output-to-string1277 (lambda () (write f))))1278s ==> "#,(foo 1 2 3)"1279(equal? f (with-input-from-string1280 s read))) ==> #t1281</enscript>12821283=== Other forms12841285==== include12861287<macro>(include STRING)</macro>12881289Include toplevel-expressions from the given source file in the currently1290compiled/interpreted program. If the included file has the extension1291{{.scm}}, then it may be omitted. The file is searched for in the1292current directory and all directories specified by the {{-include-path}}1293option.12941295==== include-relative12961297<macro>(include-relative STRING)</macro>12981299Works like {{include}}, but the filename is searched for relative to the1300including file rather than the current directory.130113021303=== Making extra libraries and extensions available13041305==== require-extension13061307<macro>(require-extension ID ...)</macro>13081309This is equivalent to {{(require-library ID ...)}} but performs an implicit1310{{import}}, if necessary. Since version 4.4.0, {{ID}} may also be an import specification1311(using {{rename}}, {{only}}, {{except}} or {{prefix}}).13121313To make long matters short - just use {{require-extension}} and it will normally figure everything out for dynamically1314loadable extensions and core library units.13151316This implementation of {{require-extension}} is compliant with [[http://srfi.schemers.org/srfi-55/srfi-55.html|SRFI-55]]1317(see the [[http://srfi.schemers.org/srfi-55/srfi-55.html|SRFI-55]] document for more information).131813191320==== require-library13211322<macro>(require-library ID ...)</macro>13231324This form does all the necessary steps to make the libraries or extensions given1325in {{ID ...}} available. It loads syntactic extensions, if needed and generates1326code for loading/linking with core library modules or separately installed1327extensions.13281329During interpretation/evaluation {{require-library}} performs one of the1330following:13311332* If {{ID}} names a built-in feature, then nothing is done.1333* If {{ID}} names one of the syntactic extensions {{chicken-syntax chicken-ffi-syntax}}, then this extension will be loaded.1334* If {{ID}} names one of the core library units shipped with CHICKEN, then a {{(load-library 'ID)}} will be performed.1335* If {{ID}} names an installed extension with the {{syntax}} or {{require-at-runtime}} attribute, then the extensions is loaded at compile-time, probably doing a run-time {{(require ...)}} for any run-time requirements.1336* Otherwise, {{(require-library ID)}} is equivalent to {{(require 'ID)}}.13371338During compilation, one of the following happens instead:13391340* If {{ID}} names a built-in feature, then nothing is done.1341* If {{ID}} names one of the syntactic extensions {{chicken-syntax chicken-ffi-syntax}}, then this extension will be loaded at compile-time, making the syntactic extensions available in compiled code.1342* If {{ID}} names one of the core library units shipped with CHICKEN, or if the option {{-uses ID}} has been passed to the compiler, then a {{(declare (uses ID))}} is generated.1343* If {{ID}} names an installed extension with the {{syntax}} or {{require-at-runtime}} attribute, then the extension is loaded at compile-time, and code is emitted to {{(require ...)}} any needed run-time requirements.1344* Otherwise {{(require-library ID)}} is equivalent to {{(require 'ID)}}.13451346{{ID}} should be a pure extension name and should not contain any path prefixes (for example {{dir/lib...}} is illegal).13471348{{ID}} may also be a list that designates an extension-specifier. Currently the following extension specifiers are1349defined:13501351* {{(srfi NUMBER ...)}} is required for SRFI-55 compatibility and is fully implemented1352* {{(version ID NUMBER)}} is equivalent to {{ID}}, but checks at compile-time whether the extension named {{ID}} is installed and whether its version is equal or higher than {{NUMBER}}. {{NUMBER}} may be a string or a number, the comparison is done lexicographically (using {{string>=?}}).13531354=== Process shutdown13551356==== emergency-exit13571358<procedure>(emergency-exit [CODE])</procedure>13591360Exits the current process without flushing any buffered output (using1361the C function {{_exit}}). Note that the {{exit-handler}} is not called1362when this procedure is invoked. The optional exit status code {{CODE}}1363defaults to {{0}}.136413651366==== exit13671368<procedure>(exit [CODE])</procedure>13691370Exit the running process and return exit-code, which defaults to 01371(Invokes {{exit-handler}}).13721373Note that pending {{dynamic-wind}} thunks are ''not'' invoked when exiting your program in this way.137413751376=== exit-handler13771378<parameter>(exit-handler)</parameter>13791380A procedure of a single optional argument. When {{exit}} is called,1381then this procedure will be invoked with the exit-code as argument. The1382default behavior is to terminate the program.13831384Note that this handler is ''not'' invoked when {{emergency-exit}} is1385used.138613871388=== implicit-exit-handler13891390<parameter>(implicit-exit-handler)</parameter>13911392A procedure of no arguments. When the last toplevel expression of the1393program has executed, then the value of this parameter is called. The1394default behaviour is to invoke all pending finalizers.139513961397==== on-exit13981399<procedure>(on-exit THUNK)</procedure>14001401Schedules the zero-argument procedures {{THUNK}} to be executed before1402the process exits, either explicitly via {{exit}} or implicitly after1403execution of the last top-level form. Note that finalizers for1404unreferenced finalized data are run before exit procedures.140514061407=== System interface140814091410==== sleep14111412<procedure>(sleep SECONDS)</procedure>14131414Puts the program to sleep for {{SECONDS}}. If the scheduler is loaded1415(for example when srfi-18 is in use) then only the calling thread is put1416to sleep and other threads may continue executing. Otherwise, the whole1417process is put to sleep.141814191420=== Ports14211422==== String ports14231424===== get-output-string14251426<procedure>(get-output-string PORT)</procedure>14271428Returns accumulated output of a port created with1429{{(open-output-string)}}.143014311432===== open-input-string14331434<procedure>(open-input-string STRING)</procedure>14351436Returns a port for reading from {{STRING}}.143714381439===== open-output-string14401441<procedure>(open-output-string)</procedure>14421443Returns a port for accumulating output in a string.144414451446=== File Input/Output14471448==== flush-output14491450<procedure>(flush-output [PORT])</procedure>14511452Write buffered output to the given output-port. {{PORT}} defaults1453to the value of {{(current-output-port)}}.14541455=== Port predicates14561457==== input-port-open?14581459<procedure>(input-port-open? PORT)</procedure>14601461Is the given {{PORT}} open for input?14621463<procedure>(output-port-open? PORT)</procedure>14641465Is the given {{PORT}} open for output?14661467==== port-closed?14681469<procedure>(port-closed? PORT)</procedure>14701471Is the given {{PORT}} closed (in all directions)?14721473==== port?14741475<procedure>(port? X)</procedure>14761477Returns {{#t}} if {{X}} is a port object or {{#f}}1478otherwise.147914801481=== Built-in parameters14821483Certain behavior of the interpreter and compiled programs can be1484customized via the following built-in parameters:14851486==== case-sensitive14871488<parameter>(case-sensitive)</parameter>14891490If true, then {{read}} reads symbols and identifiers in1491case-sensitive mode and uppercase characters in symbols are printed1492escaped. Defaults to {{#t}}.149314941495==== keyword-style14961497<parameter>(keyword-style)</parameter>14981499Enables alternative keyword syntax, where {{STYLE}} may be either1500{{#:prefix}} (as in Common Lisp), which recognizes symbols beginning1501with a colon as keywords, or {{#:suffix}} (as in DSSSL), which recognizes1502symbols ending with a colon as keywords.1503Any other value disables the alternative syntaxes. In the interpreter1504the default is {{#:suffix}}.150515061507==== parentheses-synonyms15081509<parameter>(parentheses-synonyms)</parameter>15101511If true, then the list delimiter synonyms {{#\[}} {{#\]}} and {{#\{}} {{#\}}} are enabled. Defaults to {{#t}}.151215131514==== symbol-escape15151516<parameter>(symbol-escape)</parameter>15171518If true, then the symbol escape {{#\|}} {{#\|}} is enabled. Defaults to {{#t}}.151915201521---1522Previous: [[Module srfi-4]]15231524Next: [[Module (chicken bitwise)]]